//
//  NetWorkTools.swift
//  SK微博
//
//  Created by 姜胜凯 on 15/10/10.
//  Copyright © 2015年 姜胜凯. All rights reserved.
//

import UIKit
import AFNetworking
class NetWorkTools: AFHTTPSessionManager {
//单例
    static let shareTools :NetWorkTools = {
        let url = NSURL(string: "https://api.weibo.com/")
        let tools = NetWorkTools(baseURL: url)
        //AFN中的代码：
        //self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript","text/plain") as Set<NSObject>
        return tools
    }()
    
    
    //MARK:--OAuth授权
    private let clientId = "1728197297"
    private let appSecret = "28f830a19ed479a37bcd27eb6f8c1353"
    //回调地址
    let redirectUrl = "http://www.baidu.com"
    //返回oAuth授权地址
    func oAuthUrl() -> NSURL {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    //加载token
    
    func loadAccessToken(code:String , finished: (resulet :[String :AnyObject]? , error :NSError?) -> () ){
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            //print(NSString(data: JSON as! NSData, encoding: NSUTF8StringEncoding))
            print(JSON)
            finished(resulet: JSON as? [String : AnyObject] , error: nil)
            
            }) { (_, error) -> Void in
            finished(resulet: nil, error: error)
                
        }
    
    
    }
    
    
    
}
